# -*- coding: utf-8 -*-

from odoo import api
from . import controllers
from . import models
import functools
import logging
from odoo import _
from odoo.exceptions import ValidationError, UserError
_logger = logging.getLogger(__name__)


def with_redis_client(func):
    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        # 获取默认 Redis 配置
        redis_config = self.env['redis.config'].sudo().search([
            ('state', '=', 'confirm')  # 只使用已确认的配置
        ], limit=1)

        if not redis_config:
            _logger.error("未找到可用的Redis配置")
            return func(self, *args, **kwargs)

        try:
            # 使用 get_client 获取已初始化的客户端
            redis_client = redis_config.get_client()
            if not redis_client:
                raise UserError('Redis 客户端初始化失败')

            kwargs['redis_client'] = redis_client
            return func(self, *args, **kwargs)
        except Exception as e:
            _logger.error(f"Redis连接异常: {str(e)}")
            raise UserError(f'Redis连接异常: {str(e)}')

    return wrapper


setattr(api, 'with_redis_client', with_redis_client)
